package com.example.keshe0337.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.example.keshe0337.R;
import com.example.keshe0337.biz.UserService;
import com.example.keshe0337.entity.User;
import com.example.keshe0337.ui.LoginActivity;
import com.example.keshe0337.ui.MainActivity;

import java.util.Objects;

public class ProfileFragment extends Fragment {
    Context context;
    UserService userService;
    Long UID;
    TextView textName, textAge, textPhone; // ← 提升作用域
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        context = getContext();

        View view0 = inflater.inflate(R.layout.fragment_profile, container, false);

        SharedPreferences prefs = context.getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
        UID = prefs.getLong("UID", 1);
        userService = new UserService(context);
        User user;
        TextView tvMyOrders = view0.findViewById(R.id.tvMyOrders);
        TextView tvEditInfo = view0.findViewById(R.id.tvEditInfo);
        TextView tvLogout = view0.findViewById(R.id.tvLogout);
        if (!UID.equals(-1L)) {
            user = userService.getUserById(UID);
        } else {
            user = new User();
            user.setName("未登录");
            user.setPhone("空");
            user.setAge(0);
            tvEditInfo.setVisibility(View.GONE);
            tvMyOrders.setVisibility(View.GONE);
        }

        textName = view0.findViewById(R.id.textName);
        textAge = view0.findViewById(R.id.textAge);
        textPhone = view0.findViewById(R.id.textPhone);

        textName.setText(user.getName());
        textPhone.setText(user.getPhone());
        textAge.setText(user.getAge() == 0 ? "18+" : String.valueOf(user.getAge()));




        if (UID.equals(-1L)) {
            tvLogout.setText("登陆");
        } else {
            tvLogout.setText("登出");
        }

        tvMyOrders.setOnClickListener(v -> {
            FragmentTransaction transaction = requireActivity()
                    .getSupportFragmentManager()
                    .beginTransaction();
            transaction.replace(R.id.container, new OderFragment());
            transaction.addToBackStack(null); // 可选：加入返回栈
            transaction.commit();
        });

        tvEditInfo.setOnClickListener(v -> {
            updateUser(user);
        });

        tvLogout.setOnClickListener(v -> {
            Intent intent = new Intent(context, LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
        });

        return view0;

    }


    private void updateUser(User user) {
        View dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_update_user, null);
        EditText editName = dialogView.findViewById(R.id.editName);
        EditText editAge = dialogView.findViewById(R.id.editAge);
        EditText editOriginalPassword = dialogView.findViewById(R.id.editOriginalPassword);
        EditText editNewPassword = dialogView.findViewById(R.id.editNewPassword);
        editName.setText(user.getName());
        editAge.setText(user.getAge()+"");


        AlertDialog dialogHolder = new AlertDialog.Builder(context)
                .setView(dialogView)
                .create();


        Button act = dialogView.findViewById(R.id.btn_action);
        act.setOnClickListener(v -> {

            String name = editName.getText().toString().trim();
            String ageStr = editAge.getText().toString().trim();
            String newPassword = editNewPassword.getText().toString().trim();
            String originalPassword = editOriginalPassword.getText().toString().trim();

            // 简单校验
            if (name.isEmpty() || ageStr.isEmpty()) {
                Toast.makeText(context, "姓名和年龄不能为空", Toast.LENGTH_SHORT).show();
                return;
            }

            int age;
            try {
                age = Integer.parseInt(ageStr);
            } catch (NumberFormatException e) {
                Toast.makeText(context, "年龄必须是数字", Toast.LENGTH_SHORT).show();
                return;
            }

            // 修改基本信息
            user.setName(name);
            user.setAge(age);

            // 若用户输入了原密码和新密码，进行密码更新逻辑
            if (!originalPassword.isEmpty() && !newPassword.isEmpty()) {
                if (originalPassword.equals(user.getPassword())) {
                    user.setPassword(newPassword);
                } else {
                    Toast.makeText(context, "原密码不正确", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            if (!originalPassword.isEmpty() && newPassword.isEmpty() || originalPassword.isEmpty() && !newPassword.isEmpty()) {
                Toast.makeText(context, "密码填写无效", Toast.LENGTH_SHORT).show();
                return;
            }
            userService.updateUser(user);
            Toast.makeText(context, "修改成功", Toast.LENGTH_SHORT).show();
            textName.setText(user.getName());
            textPhone.setText(user.getPhone());
            textAge.setText(user.getAge() == -1 ? "18+" : String.valueOf(user.getAge()));
            dialogHolder.dismiss();

        });

        dialogHolder.show();
    }
}
